import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: a
 * Date: 2022-10-15
 * Time: 10:04
 */
//
class Message{
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    //private List<Message> list = new ArrayList<Message>();

    //将数据从服务器加载到客户端
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        List<Message> list = load();
        String respString = objectMapper.writeValueAsString(list);
        resp.getWriter().write(respString);
    }

    //客户端提交数据给服务器
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.先把body的json数据解析出来
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        //2.把这个对象保存起来, 直接存到内存中
        //list.add(message);
        save(message);
        System.out.println("message: " + message);
        //3.返回保存成功的响应
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write("{ \"ok\": 1 }");
    }

    //把当前的消息存到数据库中
    private void save(Message message){
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            //1.和数据库建立连接
            connection = DBUtil.getConnection();
            //2.构造sql语句
            String sql = "insert into message values(?, ?, ?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1, message.from);
            statement.setString(2, message.to);
            statement.setString(3, message.message);
            //3.执行sql语句
            int ret = statement.executeUpdate();
            if (ret != 1) {
                System.out.println("插入失败!");
            } else {
                System.out.println("插入成功!");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //4.关闭连接
            DBUtil.close(connection, statement, null);
        }
    }

    //从数据库中查询到记录
    private List<Message> load(){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Message> list = new ArrayList<Message>();
        try {
            //1.建立连接
            connection = DBUtil.getConnection();
            //2.构造sql语句
            String sql = "select * from message";
            statement = connection.prepareStatement(sql);
            //3.执行sql语句
            resultSet = statement.executeQuery();
            //4.遍历结果集
            while(resultSet.next()){
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                list.add(message);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //5.关闭连接
            DBUtil.close(connection, statement, resultSet);
        }
        return list;
    }
}
